package initialize

import (
	"fmt"
	"gitee.com/DonHz/electronic-business-systems/mxshop-api/user_web/global"
	"gitee.com/DonHz/electronic-business-systems/mxshop-api/user_web/proto"
	"github.com/hashicorp/consul/api"
	_ "github.com/mbobakov/grpc-consul-resolver"
	"go.uber.org/zap"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"
)

func InitSrvConnV2() {
	consulInfo := global.ServerConfig.ConsulInfo
	userConn, err := grpc.NewClient(fmt.Sprintf("consul://%s:%d/%s?wait=14s",
		consulInfo.Host, consulInfo.Port, global.ServerConfig.UserSrv.Name),
		grpc.WithTransportCredentials(insecure.NewCredentials()),
		grpc.WithDefaultServiceConfig(`{"loadBalancingPolicy": "round_robin"}`),
	)
	if err != nil {
		zap.L().Error("【InitSrvConn】连接【用户服务】失败", zap.Error(err))
		panic(err)
	}
	userSrvClient := proto.NewUserClient(userConn)
	global.UserSrvClient = userSrvClient
}

func InitSrvConn() {
	// 从注册中心获取用户服务的信息
	cfg := api.DefaultConfig()
	consulInfo := global.ServerConfig.ConsulInfo
	cfg.Address = fmt.Sprintf("%s:%d", consulInfo.Host, consulInfo.Port)

	userSrvHost := ""
	userSrvPort := 0
	client, err := api.NewClient(cfg)

	if err != nil {
		panic(err)
	}
	data, err := client.Agent().ServicesWithFilter(fmt.Sprintf("Service==%s", global.ServerConfig.UserSrv.Name))
	if err != nil {
		panic(err)
	}
	for key, value := range data {
		fmt.Println("data.key: ", key)
		userSrvHost = value.Address
		userSrvPort = value.Port
		fmt.Println("userSrvPort: ", userSrvPort)
		break
	}
	if userSrvHost == "" {
		zap.S().Panic("【InitSrvConn】连接【用户服务】失败")
		return
	}

	// 拨号连接用户grpc服务器
	userConn, err := grpc.NewClient(fmt.Sprintf("%s:%d", userSrvHost, userSrvPort),
		grpc.WithTransportCredentials(insecure.NewCredentials()))
	if err != nil {
		zap.L().Error("【InitSrvConn】拨号连接【用户服务】失败", zap.Error(err))
		return
	}
	// 生成grpc的client并调用接口
	// 问题 1、后续用户服务下线 2、改端口号  3、改Ip	->>>负载均衡
	// 这里用连接池优化一个连接被多个goroutine使用的情况
	userSrvClient := proto.NewUserClient(userConn)
	global.UserSrvClient = userSrvClient
}
